<?php

namespace Modules\Topic\Entities;

use Modules\Core\Entities\BaseEntity as Model;
use ThrowException;

use Modules\Core\Traits\Likeable;

class Topic extends Model
{
	use Likeable;

    protected $guarded = [];
    protected $table = 'topics';

    static public $resourceName = '动态';

    protected $casts = [
        'images' => 'array',
        'videos' => 'array',
    ];

    // 搜索
    public function scopeSearch($query, $key)
    {
        return $query->where('text', 'like', '%' . $key . '%');
    }

    public function scopeMainTopic($query)
    {
        return $query->whereNull('parent_id');
    }

    public function scopeCommentTopic($query)
    {
        return $query->whereNotNull('parent_id');
    }

    public function user()
    {
    	return $this->belongsTo('\Modules\User\Entities\User', 'user_id');
    }

    // public function sub_topics()
    // {
    // 	return $this->hasMany('\Modules\Topic\Entities\Topic', 'parent_id');
    // }

    // 所有下级评论 (包括子、孙代)
    public function comments()
    {
        return $this->hasMany('\Modules\Topic\Entities\Topic', 'root_id');
    }

    // 上级评论 (仅二级以上评论会有此值)
    public function parent_comment()
    {
        return $this->belongsTo('\Modules\Topic\Entities\Topic', 'parent_id')->whereNotNull('parent_id');
    }

    public function topic_tag()
    {
    	return $this->belongsTo('\Modules\Topic\Entities\TopicTag', 'tag_id');
    }

    public function topic_group()
    {
    	return $this->belongsTo('\Modules\Topic\Entities\TopicGroup', 'group_id');
    }

    static public function beforeGetList($options)
    {
    	if (@$options['tag_id']) {
    		$options['where']['tag_id'] = $options['tag_id'];
    	}
    	if (@$options['group_id']) {
    		$options['where']['group_id'] = $options['group_id'];
    	}

    	return $options;
    }
}
